package by.grsu.verkhovodko.page;


import java.text.SimpleDateFormat;
import java.util.List;



import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;

import by.grsu.verkhovodko.app.VerkhovodkoWebApplication;
import by.grsu.verkhovodko.dao.impl.TrainDao;
import by.grsu.verkhovodko.entity.Train;

public class TrainListPage extends WebPage {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7727690682860494404L;
	private final TrainDao trainDao;
	private static final SimpleDateFormat sdf = new SimpleDateFormat("DD.mm.yyyy HH:MM");
	
	public TrainListPage() {
		super();
		
		trainDao = new TrainDao(VerkhovodkoWebApplication.DATA_XML_FOLDER);
		trainTable(trainDao.getAll());
		
	}
	
	public TrainListPage(List<Train> trains) {
		super();
		trainDao = new TrainDao(VerkhovodkoWebApplication.DATA_XML_FOLDER);
		trainTable(trains);
	}
	
	
	@SuppressWarnings({ "serial", "rawtypes" })
	private void trainTable(final List<Train> trains) {
			
		add(new DataView<Train>("table-rows", new ListDataProvider<Train>(trains)) {
			
			@Override
			protected void populateItem(final Item<Train> item) {
				final Train train = item.getModelObject();

				item.add(new Label("id", train.getId()));
				item.add(new Label("destStation", train.getDestStation()));
				item.add(new Label("dateOfDeparture", sdf.format(train.getDateOfDeparture())));
				item.add(new Label("cost", train.getCost()));					
					

				
				item.add(new Link("editLink") {
					@Override
					public void onClick() {
						setResponsePage(new TrainEditPage(train));
					}
				});

				item.add(new Link("deleteLink") {
					@Override
					public void onClick() {
						trainDao.delete(train.getId());
						setResponsePage(new TrainListPage());
					}
				});
				
				
			}
		});
		add(new Link("mainPage") {
			@Override
			public void onClick() {
				setResponsePage(StartPage.class );
			}
		});
		
	}
	
}
